// 表格和分页部分
import { Table as OrgTable, Pagination, TableProps } from '@kedacom/react-next'
import React, { useEffect, useState } from 'react'
import { StyledWrap } from './style'
import { t } from 'i18next'

export type { ColumnProps } from '@kedacom/react-next'

interface ViewProps<T = any> extends TableProps<T> {
	tableDataList: T[]
	pager?: pagerProps
	minHight?: string | number
	onPageChange?: (pageIndex: number, pageSize: number) => void
}
export type pagerProps = {
	page: number
	size?: number
	total?: number
	isDisplayMsg?: boolean
}
export const defaultPage = {
	page: 1, //当前页
	size: 20, //每一页的条目
	total: 0,
	isDisplayMsg: false,
}
interface UseHookProps {
	pager?: pagerProps
	onPageChange?: Function
}

const useHook = ({ pager, onPageChange }: UseHookProps) => {
	const [tablePager, setTablePager] = useState({
		...defaultPage,
		...pager,
	})
	useEffect(() => {
		setTablePager({
			...tablePager,
			...pager,
		})
	}, [pager])

	//页码改变时重新加载
	const onHandlePageChange = (pageIndex: number = 0, pageSize: number) => {
		onPageChange && onPageChange(pageIndex, pageSize)
	}
	return {
		tablePager,
		onHandlePageChange,
	}
}

const Table = ({
	className,
	tableDataList,
	columns,
	minHight,
	pager,
	onPageChange,
	rowIdField,
	...props
}: ViewProps) => {
	const { ..._useHook } = useHook({ pager, onPageChange })
	const [startNumber, setStartNumber] = useState(1)

	useEffect(() => {
		const tablePager = _useHook.tablePager
		const start = (tablePager.page - 1) * tablePager.size + 1
		setStartNumber(start)
	}, [tableDataList, _useHook.tablePager])

	return (
		<StyledWrap minHight={minHight} className={`table-pagination ${className ? className : ''}`}>
			<OrgTable
				className="table-wrap"
				data={tableDataList}
				columns={columns}
				rowIdField={rowIdField || 'id'}
				orderStartNumber={startNumber}
				{...props}
			/>
			{pager && (
				<div className="page-wrap">
					<Pagination
						{..._useHook.tablePager}
						total={_useHook.tablePager.total ?? tableDataList.length}
						current={_useHook.tablePager.page}
						pageSize={_useHook.tablePager.size}
						isDisplayMsg={_useHook.tablePager.isDisplayMsg}
						onChange={(e, pageIndex) => _useHook.onHandlePageChange(pageIndex, _useHook.tablePager.size)}
						i18n={{ displayMsg: t('共有 xxx 条记录') }}
					/>
				</div>
			)}
		</StyledWrap>
	)
}
export default Table
